package cn.com.chaochuang.gxfdaoa.pdfserver;

import org.apache.cxf.helpers.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.jws.WebService;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 2017-12-26
 *
 * @author Shicx
 */
@WebService(serviceName = "PdfWebservice"//服务名
        , targetNamespace = "http://pdfserver.gxfdaoa.chaochuang.com.cn"//和接口定义保持一致
        , endpointInterface = "cn.com.chaochuang.gxfdaoa.pdfserver.PdfWebservice")//包名
@Component
public class PdfWebserviceImpl implements PdfWebservice {

    private final Logger logger = LoggerFactory.getLogger(PdfWebserviceImpl.class);

    @Value("${upload.word.root.path}")
    private String wordRootPath;

    @Override
    public String uploadDocFile(CxfFileWrapper fileData) {
        logger.info("--->开始上传文件");
        WebserviceResult resultInfo = new WebserviceResult();

        if (fileData == null || fileData.getFile() == null) {
            logger.info("--->上传的文件为空");
            return resultInfo.toErrorJson("参数错误");
        }

        FileOutputStream fileOutputStream = null;
        InputStream inputStream = null;
        File file = null;

        try {
            file = new File(this.getFileRootPath() + fileData.getFileName());

            if (file.exists()) {
                FileUtils.delete(file);
                logger.info("--->删除已有的文件");
            }
            file.getParentFile().mkdirs();
            if (file.createNewFile()) {
                logger.info("--->创建文件："+file.getName());
                byte[] buff = new byte[1024 * 8];
                int len;
                inputStream = fileData.getFile().getInputStream();
                fileOutputStream = new FileOutputStream(file);
                while ((len = inputStream.read(buff)) > 0) {
                    fileOutputStream.write(buff, 0, len);
                }
                logger.info("--->文件上传成功");
                return resultInfo.toSuccessJson(file.getAbsolutePath());
            } else {
                logger.info("--->创建文件失败");
                return resultInfo.toErrorJson("文件创建失败");
            }


        } catch (Exception ex) {
            if (file != null) {
                FileUtils.delete(file);
            }
            return resultInfo.toErrorJson("文件创建失败");
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public CxfFileWrapper transferAndDownload(String filePath) {
        logger.info("--->开始转换文件，路径：" + filePath);
        CxfFileWrapper fileWrapper = new CxfFileWrapper();
        if (filePath != null) {
            File wordFile = new File(filePath);
            if (wordFile.exists()) {
                int index = wordFile.getName().lastIndexOf(".");
                String fileExt = wordFile.getName().substring(index);
                String pdfFileName = UUID.randomUUID() + ".pdf";
                String pdfFilePath = getFileRootPath() + pdfFileName;
                Boolean result = false;
                //转pdf
                if (fileExt.contains(".do")) {
                    result = PDFHelper.wpsDoc2Pdf(filePath, pdfFilePath);
                } else if (fileExt.contains(".xl")) {
                    result = PDFHelper.wpsExcel2Pdf(filePath, pdfFilePath);
                } else if (fileExt.contains(".pp")) {
                    result = PDFHelper.wpsPpt2Pdf(filePath, pdfFilePath);
                }

                logger.info("--->转换结果：" + result);

                if (result) {
                    File pdfFile = new File(pdfFilePath);
                    logger.info("--->转换pdf路径：" + pdfFilePath);
                    if (pdfFile.exists()) {
                        DataHandler handler = new DataHandler(new FileDataSource(pdfFile));
                        fileWrapper.setFile(handler);
                        fileWrapper.setFileName(pdfFile.getName());
                        logger.info("--->转换成功");
                    }
                }
            } else {
                logger.info("--->文件不存在");
            }
        }
        return fileWrapper;
    }

    /**
     * 获取文件夹路径
     *
     * @return
     */
    public String getFileRootPath() {
        return this.wordRootPath + File.separator + PDFHelper.FOLDER_NAME_FMT.format(new Date()) + File.separator;
    }
}
